<template>
  <Mainframe title="客户贷款申请">


      <el-breadcrumb :separator-icon="ArrowRight"  style="background-color:#fff;padding:10px">
        <el-breadcrumb-item :to="{ path: '#' }">主页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/customer_manage' }">项目列表</el-breadcrumb-item>
        <el-breadcrumb-item>{{applyRecord.customerName}}{{applyRecord.applyAmount}}元贷款项目 <span style="margin-left:10px; color:blue">[项目ID: {{applyRecord.applyId}}]</span></el-breadcrumb-item>
      </el-breadcrumb>
    <el-page-header style="background-color:#fff;margin-top:20px;padding:10px;"  @back="goBack"></el-page-header>
    <el-form :model="applyRecord" style="padding:10px;background-color: #ffffff" label-width="120px" ref="applyFormRef"
             :rules="formValidateRule">

      <el-col>
        <el-form-item label="姓名:"  prop="customerName">
          {{applyRecord.customerName}}  <span style="margin-left:10px; color:blue"> [客户ID: {{applyRecord.customerId}}] </span>
        </el-form-item>
        <el-form-item label="身份证号码:" rules="formValidateRule.sfzNo" prop="sfzNo">
          {{applyRecord.sfzNo}}
        </el-form-item>
        <el-form-item label="性别:" prop="sex">
          {{applyRecord.sex==1?'男':'女'}}

        </el-form-item>

        <el-form-item label="贷款金额:" required prop="applyAmount">
          {{applyRecord.applyAmount}}
        </el-form-item>
        <el-form-item label="贷款期限:" required prop="terms">
          {{applyRecord.terms}}年
        </el-form-item>

        <el-form-item label="收款账号:" required prop="bankCard">
          {{applyRecord.bankCard}}
        </el-form-item>
        <el-form-item label="还款方式:" required prop="lornType">
          {{lornTypeTxt(applyRecord.lornType)}}
        </el-form-item>
        <el-form-item label="当前状态:" required prop="lornType">

          <el-timeline style="margin-top:10px;">
            <el-timeline-item
                v-for="(activity, index) in auditLog"
                :key="index"
                :timestamp="activity.timestamp"
                :type="activity.type"
            >
              {{ activity.content }}
            </el-timeline-item>
          </el-timeline>
        </el-form-item>
        <el-form-item label="取消原因" v-if="showCancelBtn">
          <el-input
              v-model="applyRecord.memo"
              :autosize="{ minRows: 2, maxRows: 4 }"
              type="textarea"
              placeholder=""
          />
        </el-form-item>

        <el-form-item label="审核意见" v-if="showAuditBtn">
          <el-input
              v-model="applyRecord.memo"
              :autosize="{ minRows: 2, maxRows: 4 }"
              type="textarea"
              placeholder=""
          />
        </el-form-item>
        <el-form-item>

          <el-button v-if="showCancelBtn" size="small" type="danger" @click="handleCancel()">取消申请
          </el-button>

          <el-button v-if="showAuditBtn" @click="handleApprove()" type="primary">审核通过</el-button>
          <el-button v-if="showAuditBtn" @click="handleDeny()" type="danger">审核拒绝</el-button>

        </el-form-item>

      </el-col>



    </el-form>

  </Mainframe>
</template>

<style scoped>
</style>

<script>


import {reactive} from "vue";
import Mainframe from "@/components/mainframe/index.vue";
import { cancelApply,getApplyRecordById ,auditDeny, auditOk} from '@/saga/APi';
import {ElMessage} from "element-plus";
import { ArrowRight } from '@element-plus/icons-vue'


export default {
  name: 'ApplyDetail',

  mounted: function () {
    var loginJson = sessionStorage.getItem("loginedUser");
    this.loginer = JSON.parse(loginJson);
    var applyId = this.$route.query.applyId;
    this.loadById(applyId);
    // setTimeout(()=>{
    //   this.checkPriv();
    // },500);

  },


  data() {
    return {
      showCancelBtn:false,
      showAuditBtn:false,
      loginer: {role:null,userId:null,name:null},
      applyRecord: {
            applyId: 31,
            sfzNo:'sdfdsfdsfdsf',
            customerName: 'xiaoming',
            createDate: new Date(),
            auditDate: new Date(),
            lornType: 1,
            applyAmount: 1000.2,
            memo: '21313132323213',
            status: null
          },
      auditLog: []
    }

  },

  components: {
    Mainframe
  },

  methods: {

    checkPriv() {

      console.log(this.applyRecord.status);
      console.log(this.loginer.role);

      if (this.loginer != null && this.loginer.role == 'customer'
          && this.loginer.userId == this.applyRecord.customerId
          && this.applyRecord.status != 6 && this.applyRecord.status != -10 ) {
        this.showCancelBtn = true;
      }
      //role check.
      if(this.loginer!=null && this.loginer.role!='customer'&& this.applyRecord.status!==6) {
        //status biz check.
        if (([0,1].indexOf(this.applyRecord.status)!==-1 && this.loginer.role==='auditor1')
          ||  ([2,3].indexOf(this.applyRecord.status)!==-1&& this.loginer.role==='auditor2')
         || ([4,5].indexOf(this.applyRecord.status)!==-1 && this.loginer.role==='auditor3')

        ) {
          this.showAuditBtn =true;
        } else {
          this.showAuditBtn =false;
        }
      } else {
        this.showAuditBtn =false;
      }

    },
    goBack() {
      this.$router.go(-1);
    },
    getBizNextEvent() {
      //1初审通过(Select) 2 合规性审核通过(Compliance) ,3信贷审批(Credit) 4 签订合同通过 (Contract) 5 贷款已发放(Repayment)

      return {
        key0: '',
        key1: 'Select',
        key2: 'Compliance',
        key3: 'Credit',
        key4: 'Contract',
        key5: 'Finance',
        key6: 'Repayment'
      }['key' + (this.applyRecord.status + 1)];

    },
    handleApprove() {
      console.log('mock approved!')

      auditOk({status: 1, applyId: this.applyRecord.applyId, event: this.getBizNextEvent()}).then((r) => {
            if (r.code === 200) {

              ElMessage.success(r.msg || '已通过')
              this.loadById(this.applyRecord.applyId);
            } else {
              ElMessage.error("接口报错")
            }
      }).catch(error => {
        //发生错误时执行的代码
        ElMessage.error("请重试!")
      })
    },

    handleCancel() {

      cancelApply({status: -10, applyId: this.applyRecord.applyId, event: 'Cancel'}).then((r) => {
        if (r.code === 200) {
          ElMessage.success("已经成功取消申请")
          this.loadById(this.applyRecord.applyId);
        } else {
          ElMessage.error("接口报错")
        }
      }).catch((error) => {
        ElMessage.error("请重试!")
      })

    },

    handleDeny() {
      auditDeny({status: -1, applyId: this.applyRecord.applyId, event: this.getBizNextEvent()}).then((r) => {
        if (r.code === 200) {

          ElMessage.success(r.msg || '已拒绝')
          this.loadById(this.applyRecord.applyId);
        } else {
          ElMessage.error("接口报错")
        }
      }).catch(error => {
        //发生错误时执行的代码
        console.log('异常响应')
        console.log(error)
      })
    },
    loadById: function (id) {
      getApplyRecordById(id).then((response) => {
        this.applyRecord = response.data;
        var timeline = [];
        if(this.applyRecord.status>=0) {
          for (var i = 0; i <= 6; i++) {
            if (this.applyRecord.status == i) {
              timeline.push({
                content: this.statusTxt(i),
                type: 'primary',
                timeline: this.applyRecord.auditDate
              });
            } else {
              timeline.push({content: this.statusTxt(i)});
            }
          }
        } else {
          timeline.push({
            content: this.statusTxt(0),
          })
          timeline.push({
            content: this.statusTxt(this.applyRecord.status),
            hollow:true,
            timeline: this.applyRecord.auditDate,
            type: 'danger',
          })
        }





        this.auditLog = timeline;
        this.checkPriv();
      }).catch(error => {
        //发生错误时执行的代码
        console.log('异常响应')
        console.log(error)
      })
    },
    lornTypeTxt(value) {
      let statusMap = {
        key1: '等额本息',
        key2: '等额本金',
      };
      return statusMap['key' + value] || value;
    },

    statusTxt(value) {
      let statusMap = {
        'key-1': '初审拒绝',
        'key-2': '合规性审核拒绝',
        'key-3': '信贷审批拒绝',
        'key-4': '合同签订拒绝',
        'key-5': '贷款拒绝',
        'key-10': '客户取消',
        key0: '待初审',
        key1: '初审通过等待合规性审核',
        key2: '合规性审核通过待信贷审批',
        key3: '信贷审批通过待签订合同',
        key4: '合同已签订等待贷款发放',
        key5: '贷款已发放',
        key6: '已存档/结束'
      };
      return statusMap['key' + value] || value;
    },
  }
}

</script>